package com.cinc.ebc.mm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cinc.ebc.mm.constant.PurReqStatus;
import com.cinc.ebc.mm.entity.MmPurchaseRequisition;
import com.cinc.ebc.mm.entity.MmPurchaseRequisitionDetail;
import com.cinc.ebc.mm.mapper.MmPurchaseRequisitionDetailMapper;
import com.cinc.ebc.mm.mapper.MmPurchaseRequisitionMapper;
import com.cinc.ebc.mm.model.MmPurchaseRequisitionDetailModel;
import com.cinc.ebc.mm.service.IMmPurchaseRequisitionService;
import com.cinc.ebc.mm.vo.MmPurchaseRequisitionDetailPage;
import com.cinc.ebc.quote.parts.mapper.QuotePartsMapper;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 采购申请
 * @Author: jeecg-boot
 * @Date:   2022-03-20
 * @Version: V1.0
 */
@Service
public class MmPurchaseRequisitionServiceImpl extends ServiceImpl<MmPurchaseRequisitionMapper, MmPurchaseRequisition> implements IMmPurchaseRequisitionService {

	@Autowired
	private MmPurchaseRequisitionMapper mmPurchaseRequisitionMapper;
	@Autowired
	private MmPurchaseRequisitionDetailMapper mmPurchaseRequisitionDetailMapper;

	@Autowired
	private QuotePartsMapper quotePartsMapper;

	@Override
	@Transactional
	public void saveMain(MmPurchaseRequisition mmPurchaseRequisition, List<MmPurchaseRequisitionDetail> mmPurchaseRequisitionDetailList) {
		mmPurchaseRequisitionMapper.insert(mmPurchaseRequisition);
		// 保存明细
		if(mmPurchaseRequisitionDetailList!=null && mmPurchaseRequisitionDetailList.size()>0) {
			List<String> quotePartsIdList = new ArrayList<>();
			for(MmPurchaseRequisitionDetail entity:mmPurchaseRequisitionDetailList) {
				//外键设置
				entity.setPid(mmPurchaseRequisition.getId());
				mmPurchaseRequisitionDetailMapper.insert(entity);

				if(oConvertUtils.isNotEmpty(entity.getQuotePartsId())){
					quotePartsIdList.add(entity.getQuotePartsId());
				}
			}
			//更新报价零部件需求
			if(oConvertUtils.listIsNotEmpty(quotePartsIdList)){
				quotePartsMapper.autoUpdateQtyBatch(quotePartsIdList);
				quotePartsMapper.autoUpdateStatusBatch(quotePartsIdList);
			}
		}
	}

	@Override
	@Transactional
	public void updateMain(MmPurchaseRequisition mmPurchaseRequisition,List<MmPurchaseRequisitionDetail> mmPurchaseRequisitionDetailList) {
		mmPurchaseRequisition.setCreateBy(null);
		mmPurchaseRequisition.setCreateTime(null);
		mmPurchaseRequisition.setSysOrgCode(null);
		mmPurchaseRequisitionMapper.updateById(mmPurchaseRequisition);

		//1.先删除子表数据
		mmPurchaseRequisitionDetailMapper.deleteByMainId(mmPurchaseRequisition.getId());

		//2.子表数据重新插入
		if(mmPurchaseRequisitionDetailList!=null && mmPurchaseRequisitionDetailList.size()>0) {
			List<String> quotePartsIdList = new ArrayList<>();
			for(MmPurchaseRequisitionDetail entity:mmPurchaseRequisitionDetailList) {
				//外键设置
				entity.setPid(mmPurchaseRequisition.getId());
				mmPurchaseRequisitionDetailMapper.insert(entity);

				if(oConvertUtils.isNotEmpty(entity.getQuotePartsId())){
					quotePartsIdList.add(entity.getQuotePartsId());
				}
			}

			//更新报价零部件需求
			if(oConvertUtils.listIsNotEmpty(quotePartsIdList)){
				quotePartsMapper.autoUpdateQtyBatch(quotePartsIdList);
				quotePartsMapper.autoUpdateStatusBatch(quotePartsIdList);
			}
		}
	}

	@Override
	@Transactional
	public void delMain(String id) {
		LambdaQueryWrapper<MmPurchaseRequisitionDetail> reqDetailQuery = new LambdaQueryWrapper<>();
		reqDetailQuery.eq(MmPurchaseRequisitionDetail::getPid, id);
		List<MmPurchaseRequisitionDetail> requisitionDetailList = mmPurchaseRequisitionDetailMapper.selectList(reqDetailQuery);
		mmPurchaseRequisitionDetailMapper.deleteByMainId(id);
		mmPurchaseRequisitionMapper.deleteById(id);

		// 更新报价零部件需求
		List<String> quotePartsIdList = requisitionDetailList.stream().filter(req -> oConvertUtils.isNotEmpty(req.getQuotePartsId()))
				.map(MmPurchaseRequisitionDetail::getQuotePartsId).collect(Collectors.toList());
		if(oConvertUtils.listIsNotEmpty(quotePartsIdList)){
			quotePartsMapper.autoUpdateQtyBatch(quotePartsIdList);
			quotePartsMapper.autoUpdateStatusBatch(quotePartsIdList);
		}
	}

	@Override
	@Transactional
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for(Serializable id:idList) {
			delMain(id.toString());
		}
	}

	/**
	 * 详情分页查询
	 *
	 * @param page
	 * @param mmPurchaseRequisitionDetailPage
	 * @return com.baomidou.mybatisplus.extension.plugins.pagination.Page<com.cinc.ebc.modules.mm.model.MmPurchaseRequisitionDetailModel>
	 * @throws
	 */
	@Override
	public IPage<MmPurchaseRequisitionDetailModel> detailPage(IPage<MmPurchaseRequisitionDetailModel> page, MmPurchaseRequisitionDetailPage mmPurchaseRequisitionDetailPage){
		String sql = QueryGenerator.installAuthJdbc(MmPurchaseRequisition.class);
		return page.setRecords(mmPurchaseRequisitionMapper.selectDetailList(page, mmPurchaseRequisitionDetailPage, sql));
	}

	/**
	 * 明细列表查询
	 *
	 * @param mmPurchaseRequisitionDetailPage
	 * @return void
	 * @throws
	 */
	@Override
	public List<MmPurchaseRequisitionDetailModel> detailList(MmPurchaseRequisitionDetailPage mmPurchaseRequisitionDetailPage) {
		return mmPurchaseRequisitionMapper.selectDetailList(null, mmPurchaseRequisitionDetailPage, null);
	}

	/**
	 * 删除明细
	 *
	 * @param id
	 * @return void
	 * @throws
	 */
	@Override
	@Transactional
	public void delDetail(String id) throws Exception {
		MmPurchaseRequisitionDetail mmPurchaseRequisitionDetail = mmPurchaseRequisitionDetailMapper.selectById(id);
		if(mmPurchaseRequisitionDetail == null){
			throw new RuntimeException("数据不存在，删除失败！");
		}
		if(!PurReqStatus.STATUS_01.equals(mmPurchaseRequisitionDetail.getStatus())){
			throw new RuntimeException("当前状态不能删除");
		}
		mmPurchaseRequisitionDetailMapper.deleteById(id);
		// 处理主表记录
		String pid = mmPurchaseRequisitionDetail.getPid();
		QueryWrapper<MmPurchaseRequisitionDetail> queryWrapper = new QueryWrapper<MmPurchaseRequisitionDetail>().eq("pid",pid);
		Integer detailCount = mmPurchaseRequisitionDetailMapper.selectCount(queryWrapper);
		if(detailCount == 0){
			mmPurchaseRequisitionMapper.deleteById(mmPurchaseRequisitionDetail.getPid());
		}
		// 更新报价零部件需求
		if(oConvertUtils.isNotEmpty(mmPurchaseRequisitionDetail.getQuotePartsId())){
			quotePartsMapper.autoUpdateQty(mmPurchaseRequisitionDetail.getQuotePartsId());
			quotePartsMapper.autoUpdateStatus(mmPurchaseRequisitionDetail.getQuotePartsId());
		}
	}

	@Override
	@Transactional
	public void delBatchDetail(List<String> idList) throws Exception {
		// 删除校验
		QueryWrapper<MmPurchaseRequisitionDetail> queryWrapper = new QueryWrapper<>();
		queryWrapper.in("id", idList);
		List<MmPurchaseRequisitionDetail> reqDetailList = mmPurchaseRequisitionDetailMapper.selectList(queryWrapper);
		List<String> pidList = new ArrayList<>();
		List<String> quotePartsIdList = new ArrayList<>();
		for(MmPurchaseRequisitionDetail reqDetail : reqDetailList){
			if(!PurReqStatus.STATUS_01.equals(reqDetail.getStatus())){
				MmPurchaseRequisition requisition = mmPurchaseRequisitionMapper.selectById(reqDetail.getPid());
				throw new RuntimeException("单据[" + requisition.getReqNo() + "," + reqDetail.getLineNo()  + "]当前状态不能删除");
			}
			pidList.add(reqDetail.getPid());
			if(oConvertUtils.isNotEmpty(reqDetail.getQuotePartsId())){
				quotePartsIdList.add(reqDetail.getQuotePartsId());
			}
		}
		// 删除明细
		mmPurchaseRequisitionDetailMapper.deleteBatchIds(idList);
		// 处理主表
		queryWrapper.clear();
		queryWrapper.in("pid", pidList);
		List<MmPurchaseRequisitionDetail> otherDetailList = mmPurchaseRequisitionDetailMapper.selectList(queryWrapper);
		List<String> pidListHasDetail = otherDetailList.stream().map(MmPurchaseRequisitionDetail::getPid).distinct().collect(Collectors.toList());
		List<String> pidDelList = pidList.stream().filter(pid -> !pidListHasDetail.contains(pid)).collect(Collectors.toList());
		if(oConvertUtils.listIsNotEmpty(pidDelList)){
			mmPurchaseRequisitionMapper.deleteBatchIds(pidDelList);
		}
		// 更新报价零部件需求
		if(oConvertUtils.listIsNotEmpty(quotePartsIdList)){
			quotePartsMapper.autoUpdateQtyBatch(quotePartsIdList);
			quotePartsMapper.autoUpdateStatusBatch(quotePartsIdList);
		}
	}

	@Override
	@Transactional
	public void autoUpdateStatus(List<String> idList) {
		for(String id : idList){
			MmPurchaseRequisition requisition = mmPurchaseRequisitionMapper.selectById(id);
			if(PurReqStatus.STATUS_99.equals(requisition.getStatus())){
				// 已关闭的，不处理
				continue;
			}
			List<MmPurchaseRequisitionDetail> requisitionDetailList = mmPurchaseRequisitionDetailMapper.selectByMainId(null, id);
			if(oConvertUtils.listIsEmpty(requisitionDetailList)){
				// 无明细的，不处理
				continue;
			}
			String status = requisition.getStatus();
			int completeCount = 0;
			int handleCount = 0;
			for(MmPurchaseRequisitionDetail requisitionDetail : requisitionDetailList){
				if(PurReqStatus.STATUS_02.equals(requisitionDetail.getStatus())){
					handleCount += 1;
					continue;
				}
				if(PurReqStatus.STATUS_03.equals(requisitionDetail.getStatus())){
					completeCount += 1;
					continue;
				}
			}
			if(completeCount == requisitionDetailList.size()){
				status = PurReqStatus.STATUS_03;
			}else if(handleCount > 0){
				status = PurReqStatus.STATUS_02;
			}else{
				continue;
			}

			MmPurchaseRequisition requisitionModify = new MmPurchaseRequisition();
			requisitionModify.setId(id);
			requisitionModify.setStatus(status);
			mmPurchaseRequisitionMapper.updateById(requisitionModify);
		}
	}

}
